package com.huicoo.forestmanager.widget;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.huicoo.forestmanager.CustomUtils;
import com.huicoo.forestmanager.R;
import com.huicoo.forestmanager.adapter.PatrolNeedVerifyProblemAdapter;
import com.huicoo.forestmanager.adapter.VerifyEventCommentAdapter;
import com.huicoo.forestmanager.network.bean.patrol.AttachmentEntity;
import com.huicoo.forestmanager.network.bean.patrol.PatrolEventEntity;
import com.huicoo.forestmanager.network.bean.patrol.VerifyEventCommentBean.EventCommentEntity;
import com.huicoo.forestmanager.others.EventReplyEvent;
import com.huicoo.forestmanager.others.GetCommentEvent;
import com.huicoo.forestmanager.others.MediaEvent;
import com.huicoo.forestmanager.ui.media.BrowseImageActivity;
import com.huicoo.forestmanager.util.AttachmentHelper;
import com.huicoo.forestmanager.util.DisplayUtil;
import com.huicoo.forestmanager.util.LogUtils;
import com.huicoo.forestmanager.util.StringUtil;
import com.huicoo.forestmanager.util.audio.AudioRecordDialog;
import com.huicoo.forestmanager.util.audio.PlayAudioRecordDialog;
import com.huicoo.forestmanager.util.glide.ExploreImageLoader;
import com.huicoo.forestmanager.util.toast.ToastUtils;
import com.liaoinstan.springview.container.DefaultFooter;
import com.liaoinstan.springview.utils.DensityUtil;
import com.liaoinstan.springview.widget.SpringView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2019/4/11		    Administrator
 * 事件详情
 */
public class EventDetailDialog extends AlertDialog implements View.OnClickListener {
    private RelativeLayout rl_btn;
    private SpringView spring_view;
    private EditText et_remark;
    private VerifyEventCommentAdapter commentAdapter;
    private List<EventCommentEntity> commentList;

    private String eventId;  //事件id
    private int loadPage = 1;//请求评论的页数
    private int totalNum;    //评论的总数
    private String ImagePath = "";
    private String VoicePath = "";
    private String VideoPath = "";
    private String ThumbnailPath = "";

    private OnEventReplyListener onEventReplyListener;

    public EventDetailDialog(Context context) {
        super(context, R.style.ActionSheetDialogStyle);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.widget_event_dialog_detail);

        Window win = getWindow();
        if (win != null) {
            win.getDecorView().setPadding(0, 0, 0, 0);
            WindowManager.LayoutParams lp = win.getAttributes();
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            win.setAttributes(lp);
        }
        setCanceledOnTouchOutside(false);
        setCancelable(true);

        EventBus.getDefault().register(this);
        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (EventBus.getDefault().isRegistered(EventDetailDialog.this)) {
                    EventBus.getDefault().unregister(EventDetailDialog.this);
                }
            }
        });
    }

    private void init(PatrolEventEntity item) {
        eventId = String.valueOf(item.getID());
        TextView tv_type = findViewById(R.id.tv_type);
        TextView tv_desc = findViewById(R.id.tv_desc);
        TextView tv_fold = findViewById(R.id.tv_fold);
        LinearLayout ll_attachment = findViewById(R.id.ll_attachment);
        ImageView iv_event_type = findViewById(R.id.iv_event_type);
        // 上报类型图标
        iv_event_type.setImageResource(item.getReportingType() == 1 ? R.drawable.icon_event_type2 : R.drawable.icon_event_type1);
        // 事件类型
        tv_type.setText(item.getEventType() + "  " + item.getEventChildType());
        // 事件描述
        tv_desc.setText(item.getDescription());
        if (!TextUtils.isEmpty(item.getDescription()) && item.getDescription().length() > 44) {
            tv_fold.setVisibility(View.VISIBLE);
        } else {
            tv_fold.setVisibility(View.INVISIBLE);
        }

        // 展开折叠
        tv_desc.setMaxLines(item.isFold() ? 2 : Integer.MAX_VALUE);
        tv_fold.setText(item.isFold() ? "查看全文" : "  收起  ");
        tv_fold.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                item.setFold(!item.isFold());
                tv_desc.setMaxLines(item.isFold() ? 2 : Integer.MAX_VALUE);
                tv_fold.setText(item.isFold() ? "查看全文" : "  收起  ");
            }
        });
        // 附件
        ll_attachment.removeAllViews();
        //音频附件
        if (!TextUtils.isEmpty(item.getVoicePath())) {
            String[] voicePaths = item.getVoicePath().split("\\|");
            for (String path : voicePaths) {
                if (!TextUtils.isEmpty(path)) {
                    ImageView attachmentItemView = createAttachmentItem(PatrolNeedVerifyProblemAdapter.ATTACHMENT_VOICE);
                    attachmentItemView.setImageResource(R.drawable.icon_voice);
                    attachmentItemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            EventDetailDialog.this.playVoice(path);
                        }
                    });
                    ll_attachment.addView(attachmentItemView);
                }
            }
        }
        //图片附件
        if (!TextUtils.isEmpty(item.getImagePath())) {
            String[] picPaths = item.getImagePath().split("\\|");
            for (String path : picPaths) {
                if (!TextUtils.isEmpty(path)) {
                    ImageView attachmentItemView = createAttachmentItem(PatrolNeedVerifyProblemAdapter.ATTACHMENT_IMAGE);
                    ExploreImageLoader.getInstance().loadImage(getContext(), path, attachmentItemView);
                    attachmentItemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showPic(path);
                        }
                    });
                    ll_attachment.addView(attachmentItemView);
                }
            }
        }
        //视频附件
        if (!TextUtils.isEmpty(item.getVideoPath())) {
            String[] videoPaths = item.getVideoPath().split("\\|");
            String[] thumbnailPaths = null;
            if (!TextUtils.isEmpty(item.getThumbnailPath())) {
                thumbnailPaths = item.getThumbnailPath().split("\\|");
            }
            for (int i = 0; i < videoPaths.length; i++) {
                String path = videoPaths[i];
                if (!TextUtils.isEmpty(path)) {
                    ImageView attachmentItemView = createAttachmentItem(PatrolNeedVerifyProblemAdapter.ATTACHMENT_VIDEO);
                    attachmentItemView.setImageResource(R.drawable.icon_video);
                    try {
                        if (thumbnailPaths != null) {
                            String thumbPath = thumbnailPaths[i];
                            ExploreImageLoader.getInstance().loadImage(getContext(), thumbPath, attachmentItemView);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    attachmentItemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            playVideo(path);
                        }
                    });
                    ll_attachment.addView(attachmentItemView);
                }
            }
        }

        //回复按钮
        ImageView iv_camera = findViewById(R.id.iv_camera);
        ImageView iv_record = findViewById(R.id.iv_record);
        ImageView iv_comment = findViewById(R.id.iv_comment);
        ImageView iv_passed = findViewById(R.id.iv_passed);
        ImageView iv_send = findViewById(R.id.iv_send);
        iv_camera.setOnClickListener(this);
        iv_record.setOnClickListener(this);
        iv_comment.setOnClickListener(this);
        iv_passed.setOnClickListener(this);
        iv_send.setOnClickListener(this);

        rl_btn = findViewById(R.id.rl_btn);
        et_remark = findViewById(R.id.et_remark);

        //对话
        initSpringView();
        RecyclerView rv_dialog = findViewById(R.id.rv_dialog);
        rv_dialog.setLayoutManager(new LinearLayoutManager(getContext()));
        commentList = new ArrayList<>();
        commentAdapter = new VerifyEventCommentAdapter(commentList);
        commentAdapter.setOnCommentListener(new VerifyEventCommentAdapter.OnCommentListener() {
            @Override
            public void playVoice(String path) {
                EventDetailDialog.this.playVoice(path);
            }

            @Override
            public void showPic(String path) {
                EventDetailDialog.this.showPic(path);
            }

            @Override
            public void playVideo(String path) {
                EventDetailDialog.this.playVideo(path);
            }
        });
        rv_dialog.setAdapter(commentAdapter);

        //请求第一页对话
        requestComment();
    }

    private void initSpringView() {
        spring_view = findViewById(R.id.spring_view);
        spring_view.setFooter(new DefaultFooter(getContext()));
        spring_view.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadmore() {
                //当前列表个数小于总数，翻页
                if (commentList.size() < totalNum) {
                    loadPage++;
                    requestComment();
                } else {
                    spring_view.onFinishFreshAndLoad(); //完成刷新和加载
                }
            }
        });

    }

    private ImageView createAttachmentItem(int attachmentType) {
        ImageView imageView = new ImageView(getContext());
        LinearLayout.LayoutParams layoutParams;
        // 图片附件宽度90，其他附件宽度60
        int dp90 = DensityUtil.dp2px(90);
        int dp60 = DensityUtil.dp2px(60);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        if (attachmentType == PatrolNeedVerifyProblemAdapter.ATTACHMENT_IMAGE) {
            layoutParams = new LinearLayout.LayoutParams(dp90, dp60);
        } else {
            layoutParams = new LinearLayout.LayoutParams(dp60, dp60);
        }
        layoutParams.rightMargin = DensityUtil.dp2px(10);
        imageView.setLayoutParams(layoutParams);
        return imageView;
    }

    public void showEventDetail(PatrolEventEntity entity) {
        if (entity == null) {
            return;
        }
        show();
        init(entity);

        Window win = getWindow();
        if (win != null) {
            win.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        }
    }

    public void dismissEventDetail() {
        dismiss();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_camera:
                camera();
                break;
            case R.id.iv_record:
                recordVoice();
                break;
            case R.id.iv_comment:
                clickComment();
                break;
            case R.id.iv_passed:
                verifyEvent();
                break;
            case R.id.iv_send:
                sendMessage();
                break;
            default:
                break;
        }
    }

    //打开相机
    private void camera() {
        CameraSelectionDialog dialog = new CameraSelectionDialog(getContext());
        dialog.show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void captureMediaSuccessEvent(MediaEvent event) {
        LogUtils.v("gogogo on success event = " + event.type + " -- " + event.filePath);
        String filePath = event.filePath;
        HashMap<String, String> params = new HashMap<>();
        params.put("Token", CustomUtils.getToken());
        params.put("IsCheckRepeat", "1");
        params.put("UID", CustomUtils.getUUID());
        AttachmentEntity attachmentEntity = new AttachmentEntity(event.type, AttachmentHelper.getFileName(filePath), new File(filePath));
        if (onEventReplyListener != null) {
            onEventReplyListener.uploadFile(params, attachmentEntity);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void replyEventSuccessEvent(EventReplyEvent event) {
        //刷新列表
        et_remark.setText("");
        loadPage = 1;
        ImagePath = "";
        VoicePath = "";
        VideoPath = "";
        ThumbnailPath = "";
        commentList.clear();
        commentAdapter.notifyDataSetChanged();
        requestComment();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getCommentEvent(GetCommentEvent event) {
        commentList.addAll(event.commentList);
        totalNum = event.totalNum;
        commentAdapter.notifyDataSetChanged();
        spring_view.onFinishFreshAndLoad();
        LogUtils.v("gogogo get comment success event = " + totalNum + " -- " + commentList.size());
    }

    //打开图片详情
    private void showPic(String path) {
        Bundle bundle = new Bundle();
        bundle.putString("imgUrl", path);
        Intent intent = new Intent(getContext(), BrowseImageActivity.class);
        intent.putExtras(bundle);
        getContext().startActivity(intent);
    }

    // 播放视频
    private void playVideo(String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        String fileName = StringUtil.getUrlParam(path, "filename");
        LogUtils.v("gogogo gogogo file name = " + fileName);
        if (onEventReplyListener != null) {
            onEventReplyListener.eventDetailOpenVideo(3, path, fileName);
        }
    }

    //录制音频
    private void recordVoice() {
        AudioRecordDialog dialog = new AudioRecordDialog(getContext());
        dialog.setMaxSeconds(60);
        dialog.setOnAudioRecordCompleteListener(new AudioRecordDialog.OnAudioRecordCompleteListener() {
            @Override
            public void recordComplete(String filePath, int during) {
                HashMap<String, String> params = new HashMap<>();
                params.put("Token", CustomUtils.getToken());
                params.put("IsCheckRepeat", "1");
                params.put("UID", CustomUtils.getUUID());
                AttachmentEntity attachmentEntity = new AttachmentEntity(1, AttachmentHelper.getFileName(filePath), new File(filePath));
                if (onEventReplyListener != null) {
                    onEventReplyListener.uploadFile(params, attachmentEntity);
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    //播放音频
    private void playVoice(String filePath) {
        PlayAudioRecordDialog dialog = new PlayAudioRecordDialog(getContext());
        dialog.showDialog(filePath, new PlayAudioRecordDialog.OnPlayVoiceErrorListener() {
            @Override
            public void onError() {
                ToastUtils.show("录音播放异常，请重试");
            }
        });
    }

    //点击评论按钮
    private void clickComment() {
        if (rl_btn.getVisibility() == View.VISIBLE) {
            rl_btn.setVisibility(View.GONE);
        } else {
            rl_btn.setVisibility(View.VISIBLE);
        }
    }

    //点击发送按钮
    private void sendMessage() {
        String comment = et_remark.getText().toString().trim();
        if (TextUtils.isEmpty(comment)) {
            ToastUtils.show("请输入内容");
            return;
        }
        if (onEventReplyListener != null) {
            onEventReplyListener.replyEvent(createParams(comment));
        }
    }

    //核实事件
    private void verifyEvent() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        AlertDialog verifyDialog = builder.setTitle("提醒")
                .setMessage("确认核实事件？")
                .setPositiveButton("是", (dialog, which) -> {
                    if (onEventReplyListener != null) {
                        onEventReplyListener.verifyEvent(eventId);
                    }
                }).setNegativeButton("取消", (dialog, which) -> LogUtils.v("gogogo 取消核实事件")).create();

        verifyDialog.show();
    }

    //请求评论
    private void requestComment() {
        if (onEventReplyListener != null) {
            HashMap<String, String> params = new HashMap<>();
            params.put("EventID", eventId);
            params.put("PageIndex", String.valueOf(loadPage));
            params.put("PageSize", "10");
            onEventReplyListener.getComment(params);
        }
    }

    public interface OnEventReplyListener {
        void uploadFile(HashMap<String, String> params, AttachmentEntity attachmentEntity);

        void replyEvent(HashMap<String, String> params);

        void verifyEvent(String eventId);

        void getComment(HashMap<String, String> params);

        void eventDetailOpenVideo(int type, String path, String filename);
    }

    public void setOnEventReplyListener(OnEventReplyListener onEventReplyListener) {
        this.onEventReplyListener = onEventReplyListener;
    }

    private HashMap<String, String> createParams(String description) {
        HashMap<String, String> params = new HashMap<>();
        params.put("EventID", eventId);
        params.put("Description", description);
        params.put("ImagePath", ImagePath);
        params.put("VoicePath", VoicePath);
        params.put("VideoPath", VideoPath);
        params.put("ThumbnailPath", ThumbnailPath);
        return params;
    }

    // 附件
    public void addFilePath(int attachmentType, String fileName, String ThumbnailFile) {
        if (attachmentType == 1) {
            //添加到提交参数中
            VoicePath = StringUtil.getUrlParam(fileName, "filename");
            ImagePath = "";
            VideoPath = "";
            ThumbnailPath = "";
        } else if (attachmentType == 2) {
            //添加到提交参数中
            ImagePath = StringUtil.getUrlParam(fileName, "filename");
            VoicePath = "";
            VideoPath = "";
            ThumbnailPath = "";
        } else if (attachmentType == 3) {
            //添加到提交参数中
            VoicePath = "";
            ImagePath = "";
            VideoPath = StringUtil.getUrlParam(fileName, "filename");
            ThumbnailPath = StringUtil.getUrlParam(ThumbnailFile, "filename");
        }
        if (onEventReplyListener != null) {
            onEventReplyListener.replyEvent(createParams(""));
        }
    }
}
